package org.road0329.tools.proto_parse_tool.ems.xintian;

import org.road0329.tools.proto_parse_tool.chargingpile.MsgDcsResult;
import org.road0329.tools.proto_parse_tool.ems.xintian.utils.XinTianClassOneUtil;
import org.road0329.tools.proto_parse_tool.ems.xintian.utils.XinTianClassTwoUtil;
import org.road0329.tools.proto_parse_tool.ems.xintian.utils.XinTianConfirmUtil;
import org.road0329.tools.proto_parse_tool.enums.GwAfnEnum;
import org.road0329.tools.proto_parse_tool.utils.ProtocolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2018-09-12.
 */
@Component
public class ProtocolXinTianHandle {

    private static Logger logger = LoggerFactory.getLogger(ProtocolXinTianHandle.class);

    private final short protocolid = 0x03;

    private final byte MSTA = 0x0D;

    public static MsgDcsResult decoder(byte[] msg) {
        // AFN
        int afn = ProtocolUtils.Unsignd(msg[12]);
        int seq = ProtocolUtils.Unsignd(msg[13]);
        // 6个固定字节，1个控制码，7~10地址
        boolean acd = (msg[6] & 0x20) == 0 ? false : true; // 是否有重要事件等待访问???
        boolean prm = ((msg[6] & 0x40) == 0);//0表示为终端响应报文，需要上送任务
        MsgDcsResult gwResult = null;
        try {
            switch (afn) {
                case 0x00://确认命令:00H
                    gwResult = XinTianConfirmUtil.parseACKData(msg, 13, acd);
                    gwResult.setCmdType(GwAfnEnum.AFN_CONFIRM_CMD.getValue());
                    break;
                case 0x0B://请求一类数据
                    gwResult = XinTianClassOneUtil.parseClassOneData(msg, 13, acd);
                    gwResult.setCmdType(GwAfnEnum.AFN_REQ_1ST_DATA.getValue());
                    break;
                case 0x0C://请求二类数据
                    gwResult = XinTianClassTwoUtil.parseClassTwoData(msg, 13, acd);
                    gwResult.setCmdType(GwAfnEnum.AFN_REQ_2ND_DATA.getValue());
                    break;
            }
            gwResult.setSuccess(true);
            gwResult.setErrorCode(afn); //用于web解析终端扩展命令
            gwResult.setReceiveMsg(ProtocolUtils.printMsg(0, msg.length, msg));
        } catch (Exception e) {
            gwResult = new MsgDcsResult();
            gwResult.setSuccess(false);
            //设成确认帧
            gwResult.setCmdType(GwAfnEnum.AFN_CONFIRM_CMD.getValue());
            gwResult.setMessage("命令解析出错:" + e.getMessage());
        }
        if (prm) {
            gwResult.setPrm(true);
        }
        return gwResult;
    }
}
